//
//  CommFunc.cpp
//  irisx
//
//  Created by Paladin on 13-3-7.
//
//
#include "CommFunc.h"
#include <stdlib.h>
#include "string.h"
#include <assert.h>
#include <zlib.h>
#include <stream.h>
 

int zlib_compress(unsigned char** dest, const char* src)
{
    int ret = -1;
    uLongf buffSize = 0;
    int srcSize = strlen(src);
    buffSize = compressBound(srcSize);
    unsigned char* buff = (unsigned char*)malloc(srcSize);
    assert(buff);
    ret = compress(buff, &buffSize, (unsigned char*)src, srcSize);
    *dest = buff;
    ret = buffSize;
    return ret;
}

int zlib_uncompress(unsigned char** dest, const char* src, int srcLen)
{
    int ret = -1;
    int srcSize = srcLen;
    int count = 1;
    uLongf buffSize = 0;
    unsigned char* buff = NULL;
    do {
        count++;
        buffSize = srcSize * count;
        buff = (unsigned char*)malloc(buffSize);
        assert(buff);
        memset(buff, 0x00, buffSize);
        ret = uncompress(buff, &buffSize, (unsigned char*)src, srcLen);
        if (ret == Z_OK || ret == Z_DATA_ERROR)
            break;
        else {
            free(buff);
            buff = NULL;
        }
    }while (1);
    *dest = buff;
    ret = buffSize;
    return ret;
}

int zlib_uncompress2(unsigned char** dest, int destLen, const char* src, int srcLen)
{
    int ret = -1;
    uLongf buffSize = destLen + 1;
    unsigned char* buff = NULL;
    
    *dest = NULL;
    buff = (unsigned char*)malloc(buffSize);
    assert(buff);
    memset(buff, 0x00, buffSize);
    ret = uncompress(buff, &buffSize, (unsigned char*)src, srcLen);
    if (ret == Z_OK)
    {
        *dest = buff;
        ret = buffSize;
    }
    return ret;
}


unsigned int utf8StringOfCharCount(const char* str)
{
    int i = 0;
    unsigned int result = 0;
    
    while (str[i])
    {
        if ((str[i] & 0xc0) != 0x80) // 找到一个字符
            result++;
        i++;
    }
    return result;
}


bool _find(char *pStart,  char* subString)
{
    int subLen = 0;
    subLen = (int)strlen(subString);
    
    for (int  i = 0; i < subLen; i++)
    {
        if (pStart[i] != subString[i])
            return false;
    }
    return true;
}

//
unsigned int findx_subString(char* source, char* subString)
{
    int i = 0;
    unsigned int result = 0;
    while (source[i])
    {
        if ((source[i] & 0xC0) != 0x80) // 找到一个字符
        {
            result++;
            if(_find(&source[i], subString))
                return result;
        }
        i++;
    }
    return 0;
}

